package com.jade.bss.web.controller;

import com.jade.bss.admin.account.AdminAccount;
import com.jade.bss.security.shiro.authc.SysAdminPasswordToken;
import com.jade.bss.web.resolver.AdminCapsule;
import com.jade.bss.web.vo.LoginRequest;
import com.jade.framework.security.shiro.authc.SessionIdToken;
import com.jade.framework.base.util.ResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping (value = "/admin")
@Api(value="登录接口", description="管理员登录接口")
public class AdminLoginController
{
    protected Log logger = LogFactory.getLog(getClass());

    @RequestMapping(value={"/login"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
    @ApiOperation(value="登录", httpMethod="POST")
    public void login(@ApiParam("帐户信息") @RequestBody LoginRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated())
            {
                SysAdminPasswordToken token = new SysAdminPasswordToken();
                token.setUsername(request.getUsername());
                token.setPassword(request.getPassword().toCharArray());
                subject.login(token);
                this.logger.info(request.getUsername() + " login");
            }
            String token = subject.getSession().getId().toString();
            AdminAccount adminAccount = (AdminAccount)subject.getPrincipal();
            Map map = new HashMap();
            map.put("token", token);
            map.put("adminAccount", adminAccount);
            ResponseUtils.writeSuccessResult(response, map);
        }
        catch (Exception ex)
        {
            this.logger.error("login error:", ex);
            ResponseUtils.writeErrorResult(response, 401, "err.bss.admin.account.auth_fail", "invalid username or password", new Object[0]);
        }
    }

    @RequestMapping(value={"/sessionLogin"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
    @ApiOperation(value="登录", httpMethod="POST")
    public void sessionLogin(@RequestParam("sid") String sid, @RequestParam("call_back_url") String callbackUrl, HttpServletResponse response)
            throws Exception
    {
        Subject subject = SecurityUtils.getSubject();
        SessionIdToken token = new SessionIdToken();
        token.setSessionId(sid);
        subject.login(token);
        if (StringUtils.isEmpty(callbackUrl))
        {
            AdminAccount adminAccount = (AdminAccount)subject.getPrincipal();
            Map map = new HashMap();
            map.put("token", sid);
            map.put("adminAccount", adminAccount);
            ResponseUtils.writeSuccessResult(response, map);
        }
        else
        {
            response.sendRedirect(callbackUrl);
        }
    }

    //@RequiresAuthentication
    @RequestMapping(value={"/checkLogin"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
    @ApiOperation(value="检查登录", httpMethod="GET")
    public void checkLogin(HttpServletResponse response)
            throws Exception
    {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated())
        {
            String token = subject.getSession().getId().toString();
            AdminAccount adminAccount = (AdminAccount)subject.getPrincipal();
            Map map = new HashMap();
            map.put("token", token);
            map.put("adminAccount", adminAccount);
            ResponseUtils.writeSuccessResult(response, map);
        }
    }

    @ResponseBody
    @RequiresAuthentication
    @RequestMapping({"/logout"})
    @ApiOperation(value="登出", httpMethod="GET")
    public void logout(HttpServletRequest request, HttpServletResponse response, AdminCapsule capsule)
            throws Exception
    {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        Map map = new HashMap();
        if (capsule != null)
        {
            AdminAccount account = capsule.unwrap();
            if (account != null) {
                this.logger.info(account.getName() + " logout");
            }
            map.put("logout", "true");
            ResponseUtils.writeSuccessResult(response, map);
        }
        else
        {
            this.logger.info("unknown admin logout");
            map.put("logout", "false");
            ResponseUtils.writeSuccessResult(response, map);
        }
    }
}
